<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/4/20
 * Time: 18:16
 */

namespace app\index\controller;


use think\Cache;
use think\Controller;
use expressage\Expressage;
use app\index\model\CrmOrder;
use app\index\model\CrmOrderGoods;
use think\Db;
use app\index\model\CrmRegion;
use app\index\model\CrmProduct;

class Express extends Base
{
    public $crmOrderModel;
    public $expressage;


    /*
     * 物流发货列表
     * */
    public function logistics(){
        $query = input();
        $query['rows'] = isset($query['rows'])?$query['rows']:10;
        $query['page'] = isset($query['page'])?$query['page']:1;
        $orderModel = new CrmOrder();
        $res = $orderModel->logistics($query);
        foreach ($res['list'] as $key=>&$value){
            $value['goods_name']='';
            foreach ($value['items'] as $val){
                $value['goods_name'].=$val['goods_name'].'。';
            }
           unset($value['items']);
        }
        apiReturn(200,'',$res);
    }


    public function common(){
        $data = input();
        if(!isset($data['ids']) ||  empty($data['ids']))apiReturn(200,'缺少参数');
        $ids = $data['ids'];
        if(!is_array($ids) || count($ids)<1)apiReturn(200,'格式上传错误');
        $this->crmOrderModel = new CrmOrder();
        $this->expressage = new Expressage();
        $orderArr = $this->crmOrderModel->where('id','in',$ids)->select();
        return $orderArr;
    }

    /*
     * 创建快递单
     * */
    public function create(){
        $id = [];
        $orderArr = $this->common();
        $times = time();
        foreach ($orderArr as &$value){
            if(!empty($value['express_number'])) apiReturn(400,'订单ID为：'.$value['orderid']."已经发货");
            if($value['check_status']!=4)apiReturn(400,'订单ID为：'.$value['orderid']."该订单还未审核");
            if(empty($value['province']) || empty($value['city']) || empty($value['area']) || empty($value['address'])){
                apiReturn(400,'订单ID为：'.$value['orderid']."发送地址不全");
            }elseif (($int = (int)$value['province'])!=0){
                $value['province'] =  $this->address($int,$value['orderid']);
                $value['city'] =  $this->address( (int)$value['city'],$value['orderid']);
                $value['area'] =  $this->address( (int)$value['area'],$value['orderid']);
            }
            if(empty($value['phone']))apiReturn(400,'订单ID为：'.$value['orderid']."缺少手机号");
        }
        foreach ($orderArr as $val){
            $result = $this->expressage->createOrder($val['name'],$val['phone'],$val['province'],$val['city'],$val['area'],$val['address']);
            if(is_string($result) || $result==null) {
                express('订单ID为：'.$val['orderid'].'中通接口错误：',$result,'express');
                continue;
            }
            if(!$this->crmOrderModel->where('express_number',$result['billCode'])->find()){
                $res = $this->crmOrderModel->allowField(['order_status','express_number','express_time'])->update(['express_time'=>$times,'express_number'=>$result['billCode']], ['id' => $val['id']]);
            }
            if(!isset($res) || !$res) express('订单ID为：'.$val['orderid'].'数据库更新失败','express');
            array_push($id,['id'=>$val['orderid']]);
        }
        if(count($id)<1)apiReturn(400,'快递订单创建失败');
        apiReturn(200,'快递订单创建成功',$id);
    }

    public function address($int,$orderid){
        $region = CrmRegion::get($int);
        if(!$region) apiReturn(400,'订单ID为：'.$orderid."；发货地址错误");
        return $region->region_name;
    }

    /*
     *云打印
     *  */
    public function cloudPrint(){
        $id = [];
        if(!Cache::has('deviceId') ||  !Cache::has('qrcodeId')){
            apiReturn(400,'请先配置打印机');
        }
        $orderArr = $this->common();
        foreach ($orderArr as $value){
            if(empty($value['express_number']))apiReturn(400,'订单ID为：'.$value['orderid']."无运货单号");
        }
        $crmOrderGoodsModel = new CrmOrderGoods();
        foreach ($orderArr as $val){
            $goods_name = $crmOrderGoodsModel->where('order_id','=',$val['orderid'])->column('goods_name');
            $name = $goods_name[0];
            if(count($goods_name)>1)$name = implode('，',$goods_name);
//            if (($int = (int)$val['province'])!=0){
//                $val['province'] =  $this->address($int,$val['orderid']);
//                $val['city'] =  $this->address( (int)$val['city'],$val['orderid']);
//                $val['area'] =  $this->address( (int)$val['area'],$val['orderid']);
//            }
            $receiver=['name'=>$val['name'],'mobile'=>$val['phone'],'prov'=>$val['province'],'city'=>$val['city'],'county'=>$val['area'],'address'=>$val['address']];
            $result = $this->expressage->batchCloudPrint($val['express_number'],$name,$receiver);
            if(is_string($result) || $result==null) {
                express('订单ID为：'.$val['orderid'].'中通接口错误：',$result,'express');
                continue;
            }
            array_push($id,['id'=>$val['orderid']]);
        }
        if(count($id)<1)apiReturn(400,'打单失败');
        apiReturn(200,'打单成功',$id);
    }

    /*
     * 配置
     * */
    public function prints(){
        $data = input();
        if(!isset($data['deviceId']) || !isset($data['qrcodeId']))apiReturn(400,'缺少参数');
        Cache::set('deviceId',$data['deviceId']);
        Cache::set('qrcodeId',$data['qrcodeId']);
        apiReturn(200,'已配置');
    }

    /*
     * 日志
     * */
    public function log(){
       $express_log =  RUNTIME_PATH.'express.log';
      // if(!is_file($express_log))apiReturn(400,'暂无日志内容');
        $str='';
        if (file_exists($express_log)) {
            $fp = fopen($express_log, "r");
            $str = fread($fp, filesize($express_log));//指定读取大小，这里把整个文件内容读取出来
             $str = str_replace("\r\n", "<br />", $str);
        }
        $arr = explode("------------------------ --------------------------", $str);
        $arr = array_reverse($arr);
        apiReturn(200,'成功',implode('------------------------ --------------------------',$arr));
    }



    /*
     * 物流轨迹
     * */
    public function trackQuery(){
        $billCode = input('billCode');
        if(empty($billCode))apiReturn(400,'请上传快递单号');
        $expressage = new Expressage();
        //$billCode='73100059800035';
        $res = $expressage->trackQuery($billCode);
        if(is_string($res)) apiReturn(400,$res);
        if(count($res)<1)apiReturn(400,'无物流信息');
        $path = '';
        $res =  array_reverse($res);
        foreach ($res as $value){
            $path .=date('Y年m月d日 H:i:s',$value['scanDate']/1000)."<br>".$value['desc']."<br>";
        }
        apiReturn(200,'',$path);
    }

    public function trac(){
        new Expressage(1);
    }

    /*
     * 打印机
     * */
    public function getPrints(){
        if(Cache::has('deviceId') ||  Cache::has('qrcodeId')){
            apiReturn(200,'',['deviceId'=>Cache::get('deviceId'),'qrcodeId'=>Cache::get('qrcodeId')]);
        }
    }

    /*
     * 货物
     * */
    public function product(){
        apiReturn(200,'成功',CrmProduct::field('id,name,sn')->select());
    }

    /*
     * 修改状态
     * */
    public function status_order(){
        $data = input();
        $orderModel = new CrmOrder();
        if(isset($data['orderid'])){
            if(!is_array($data['orderid']) || count($data['orderid'])<=0)apiReturn(400,'参数错误');
        }else{
            apiReturn(400,'缺少参数');
        }
        foreach ($data['orderid'] as $value){
            $order_status = $orderModel->where('orderid',$value)->value('order_status');
            if($order_status==5) apiReturn(400,'订单ID:'.$value.'已经交易完成');
        }
        if(!$orderModel->isUpdate(true)->where('orderid','in',$data['orderid'])->update(['order_status'=>4])){apiReturn(400,'失败');}
        apiReturn(200,'成功');
    }




}